import { getshopListByGood, getGoodDetail } from '@mall/api/good'
import { preOrderFun } from '@mall/api/order'
import { addGoodsToCart } from '@mall/api/shopCart'
import { getDistance } from "@src/common/utils";
import mall from "@src/store/mall";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import router from "@src/router";
import base from "@src/store/base";

Component({
  options: {
    multipleSlots: true,
    addGlobalClass: true
  },
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: ['curLocation', 'userLocation', 'chooseAddress'],
    actions: ['setStoreId']
  }, {
    store: base,
    fields: ['isiPhoneX', 'themeColor', 'themeTitleColor']
  }],
  properties: {
    goodsId: {
      type: Number
    },
    skuInfo: {
      type: Object
    },
    snCode:{
      type:String
    }
  },
  data: {
    dialogShow: false,
    filterMarkShow: false,
    contentHeight: 300,
    initForm: {},
    originStoreList: [],
    storeList: [],
    filterForm: null,
    collList:[], //搭配商品组
    filterList: [{
      id: "sort",
      title: "智能排序",
      type: "single",
      exclusion: ["distance"],
      data: [
        { id: 0, title: "智能排序", noActive: true },
        { id: 1, title: "价格从低到高" },
        { id: 2, title: "价格从高到低" }
      ]
    }, {
      id: "distance",
      title: "距离远近",
      type: "single",
      exclusion: ["sort"],
      data: [
        { id: 0, title: "距离远近", noActive: true },
        { id: 1, title: "离我定位近的" },
        { id: 2, title: "离收货地址近的" }
      ]
    }, {
      id: "buyWay",
      title: "购买方式",
      type: "single",
      data: [{ id: '', title: "全部", subTitle: '购买方式', noActive: true },
      { "id": "EXPRESS", "title": "直邮到家" },
      { "id": "LOCAL", "title": "同城配送" },
      { "id": "SELF_PICKUP", "title": "到店自提" },
      ]
    }],
    currentStoreId:''
  },
  observers: {
    'userLocation,chooseAddress': function () {
      this.filterStoreList();
    },
  },
  lifetimes: {
    attached() {
      let goodsId = this.data.goodsId;
      let skuInfo = this.data.skuInfo;
      let skuId = skuInfo.skuList[0].skuId
      this.fetchData(goodsId, skuId)
    }
  },
  methods: {
    open(options) {
      this.fetchData(options.goodsId, options.skuId);
      this.setData({
        goodsSerial: options.goodsSerial,
        virtual: options.virtual,
        skuNum: options.skuNum,
        skuId: options.skuId,
        selectSkuObj: options.selectSkuObj,
        dialogShow: true,
        initForm: {},
        currentStoreId:options.currentStoreId
      })
    },
    fetchData(goodsId, skuId) {
      this.updateStoreBindings();
      let params = { goodsId, skuId }
      getshopListByGood(params).then(res => {
        this.setData({ originStoreList: res.data })
        this.triggerEvent('storelist', res.data)
        this.filterStoreList();
      })
    },
    handleChangeStore(e) {
      let store = e.currentTarget.dataset.store
      wx.showModal({
        title: "温馨提示",
        content: "是否切换到店铺 - " + store.name + " ?",
        cancelText: "取消",
        confirmText: "确定",
        success: (sm) => {
          if (sm.confirm) {
            this.triggerEvent('change', store)
            this.setData({ dialogShow: false })
          }
        }
      });
    },
    handleFilterStatus(e) {
      this.setData({ filterMarkShow: !!e.detail })
    },
    handleFilterClose(e) {
      this.setData({ filterMarkShow: false })
      this.selectComponent("#goodsFilter").close();
    },

    handleFilterChange(e) {
      this.setData({ filterForm: e.detail })
      this.filterStoreList()
    },
    handleContentHeight(e) {
      this.setData({ contentHeight: e.detail })
    },

    filterStoreList() {
      this.updateStoreBindings();
      let originStoreList = this.data.originStoreList;
      if (!originStoreList || originStoreList.length === 0) {
        this.setData({ storeList: [] })
        return;
      }

      let filterForm = this.data.filterForm;
      let buyWay = (filterForm && filterForm['buyWay']) ? filterForm['buyWay'].value : ''
      let sort = (filterForm && filterForm['sort']) ? filterForm['sort'].value : 0
      let distance = (filterForm && filterForm['distance']) ? filterForm['distance'].value : 0
      let list = []

      for (let i = 0; i < originStoreList.length; i++) {
        let store = originStoreList[i]
        if (this.data.curLocation) {
          store['distance'] = getDistance(store.latitude, store.longitude,
            this.data.curLocation.latitude, this.data.curLocation.longitude)
        } else {
          store['distance'] = -1
        }
        if (this.data.userLocation) {
          store.userDistance = getDistance(store.latitude, store.longitude,
            this.data.userLocation.latitude, this.data.userLocation.longitude)
        } else {
          store['userDistance'] = -1
        }
        if (this.data.chooseAddress) {
          store['addressDistance'] = getDistance(store.latitude, store.longitude,
            this.data.chooseAddress.latitude, this.data.chooseAddress.longitude)
        } else {
          store['addressDistance'] = -1
        }
        if (!buyWay) {
          list.push(store)
        } else if (buyWay === 'EXPRESS' && store.supplyExpress) {
          list.push(store)
        } else if (buyWay === 'LOCAL' && store.supplyLocalDelivery) {
          list.push(store)
        } else if (buyWay === 'SELF_PICKUP' && store.supplySelfPickup) {
          list.push(store)
        }
      }
      if (sort === 2) {
        list.sort(function (a, b) {
          return b.price - a.price
        });
      }
      if (sort === 1) {
        list.sort(function (a, b) {
          return a.price - b.price
        });
      }
      // 排序
      list.sort((a, b) => {
        if (distance === 1 && this.data.userLocation) {
          return a.userDistance - b.userDistance
        } else if (distance === 2 && this.data.chooseAddress) {
          return a.addressDistance - b.addressDistance
        }
        return a.distance - b.distance
      });
      this.setData({ storeList: list })
    },

    handleBuyNow(e) {
      let store = e.currentTarget.dataset.item
      let storeId = e.currentTarget.dataset.item.storeId
      if (this.data.virtual) {
        // 虚拟商品下单,发预下单请求跳到预下单页面
        this.buyVirtualGoods(storeId);
        return;
      }
      this.setData({
        currentStoreId: storeId,
        currentItem: store
      })
      //发请求这个店铺的sku数据
      let params = {
        goodsSerial: this.data.goodsSerial,
        storeId: storeId
      }
      getGoodDetail(params).then(res => {
        let curGoodsObj = res.data
        let deliveryType = null;
        if (curGoodsObj.goodsDelivery && curGoodsObj.goodsDelivery.length > 0) {
          deliveryType = curGoodsObj.goodsDelivery[0].deliveryType;
        }
        let selectSkuObj = this.data.selectSkuObj;
        if (selectSkuObj == null || (selectSkuObj.status !== 1 || selectSkuObj.stockNum <= 0)) {
          // 选择新的sku
          let newSku = null;
          let skuList = curGoodsObj.skuInfo.skuList;
          for (let i = 0; i < skuList.length; i++) {
            let sku = skuList[i];
            if (sku.status === 1 && sku.stockNum > 0) {
              newSku = sku;
              break
            }
          }
          if (newSku) {
            this.setData({ selectSkuObj: newSku })
          }
        }
        console.log("curGoodsObj", curGoodsObj)
        this.setData({ curGoodsObj: curGoodsObj, deliveryType: deliveryType,goodsBargains:curGoodsObj.goodsBargains, })
        wx.nextTick(() => {
          this.setData({ skuDialogShow: true })
        })
      })
    },
    buyVirtualGoods(storeId) {
      let dataTemp = {}
      let items = []
      let deliveryType = "VIRTUAL";
      let orderPreForm = {
        goodsId: this.data.goodsId,
        num: 1,
        skuId: this.data.skuId,
        storeId: storeId
      }
      items.push(orderPreForm)
      dataTemp.items = items;
      dataTemp.source = 1;
      dataTemp.storeId = storeId
      dataTemp.type = deliveryType
      preOrderFun(dataTemp).then(res => {
        if (res.code === 0) {
          router.push({ name: 'mall/submit-order-virtual', params: { preNo: res.data.preNo } })
        } else {
          wx.showToast({
            title: '购买失败，晚点试试把',
            icon: 'none',
            duration: 3000
          })
        }
      })
    },
    minirorAddcoll(e){
        this.setData({collList:e.detail})
    },
    skuObjFun(e) {
      if (e.detail) {
        this.setData({
          selectSkuObj: e.detail,
          snCode:e.detail.sn
        });
      }
    },
    // specBuyNowFunc(details){
    //   this.triggerEvent("specBuyNowFunc",details.detail)
    // },
    specBuyNowFunc(detail) {
      let num = 1;
      if (detail.detail) {
        num = detail.detail.count
      }
      //声明参数
      let dataTemp = {}
      let items = []
      let orderPreForm = {
        goodsId: this.data.goodsId,
        num: num,
        skuId: this.data.selectSkuObj.skuId ? this.data.selectSkuObj.skuId : this.data.skuList[0].skuId,
        storeId: this.data.currentStoreId
      }
      items.push(orderPreForm)
      dataTemp.items = items;
      dataTemp.source = 1;
      dataTemp.storeId = this.data.currentStoreId
      dataTemp.type = this.data.deliveryType
      dataTemp.subType = this.data.curGoodsObj.presell ? 'PRESELL' : "";
      dataTemp.items[0].children = this.data.collList;
      preOrderFun(dataTemp).then(res => {
        if (res.code === 0) {
          router.push({ name: 'mall/submit-order', params: { preNo: res.data.preNo ,snCode:this.data.snCode} })
        }
      })
    },
    handleDeliveryType(e) {
      this.setData({ deliveryType: e.detail })
    },
    //监听子组件加入购物车事件
    addCart(count) {
      console.log('detail', count.detail);
      let tempData = {
        goodsId: this.data.goodsId,
        num: count.detail ? count.detail : 1,
        skuId: this.data.selectSkuObj.skuId,
        snCode:this.data.selectSkuObj.sn,
        storeId: this.data.currentStoreId,
        cartType: 0,
        type: this.data.deliveryType
      };
      addGoodsToCart(tempData).then(res => {
        if (res.code === 0) {
          // 修改当前店铺
          this.setStoreId(tempData.storeId)
          wx.showToast({
            title: "加入购物车成功",
            icon: 'none'
          })
        } else {
          wx.showToast({
            title: "加入购物车失败",
            icon: 'none'
          })
        }
        console.log('res', res)
      })

    },
    stopMove() {

    }
  },

})
